package com.woyowodaows.utils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Point;
import android.os.Build;
import android.os.IBinder;
import android.support.design.widget.TabLayout;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.gyf.barlibrary.ImmersionBar;
import com.woyowodaows.R;


import java.lang.reflect.Field;

/**
 * @author haiwei
 *         分辨率转换工具(沉淀状态设置)
 *         2017-2-22
 */
public class DisplayUtils {


    /**
     * 设置透明沉浸式状态栏 当系统大于或等于4.4
     *
     * @param context
     */
    public static void setTransparencyStatusBar(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            ImmersionBar.with((Activity) context).statusBarColor(R.color.colorPrimaryGreen).init();
        }
    }

    public static void setTransparencyStatusBar(Context context, boolean isDarkFont, int colorId) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ImmersionBar.with((Activity) context).statusBarColor(colorId).statusBarDarkFont(isDarkFont).init();
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            ImmersionBar.with((Activity) context).statusBarColor(R.color.text_gray_333).init();
        }
    }

    /**
     * 关闭沉浸式状态栏
     *
     * @param context
     */
    public static void closeTransparencyStatusBar(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            ImmersionBar.with((Activity) context).destroy(); //必须调用该方法，防止内存泄漏
        }
    }

    /**
     * 显示软键盘
     */
    public static void showSoftInput(Context context) {
        InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethodManager != null) {
            View localView = ((Activity) context).getCurrentFocus();
            if (localView != null && localView.getWindowToken() != null) {
                inputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    /**
     * 隐藏软键盘
     */
    public static void hideSoftKeyboard(View view, Context context) {
        if (view == null) {
            return;
        }
        InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethodManager != null) {
            IBinder localIBinder = view.getWindowToken();
            if (localIBinder != null)
                inputMethodManager.hideSoftInputFromWindow(localIBinder, 0);
        }
    }

    /**
     * 获取状态栏高度
     *
     * @param context
     * @return
     */
    public static int getStatusBarHeight(Context context) {
        int statusBarHeight = -1;
        try {
            Class<?> clazz = Class.forName("com.android.internal.R$dimen");
            Object object = clazz.newInstance();
            int height = Integer.parseInt(clazz.getField("status_bar_height")
                    .get(object).toString());
            statusBarHeight = context.getResources().getDimensionPixelSize(height);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return statusBarHeight;
    }

    /**
     * dip转px
     *
     * @param context
     * @param dipValue
     * @return
     */
    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    /**
     * px转dip或dp值，保证尺寸大小不变
     *
     * @param context
     * @param pxValue
     * @returnjava.lang.String
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 将px值转换为sp值，保证文字大小不变
     *
     * @param pxValue
     * @param context （DisplayMetrics类中属性scaledDensity）
     * @return
     */

    public static int px2sp(Context context, float pxValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    /**
     * 将sp值转换为px值，保证文字大小不变
     *
     * @param spValue （DisplayMetrics类中属性scaledDensity）
     * @return
     */
    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    /**
     * 获取屏幕宽度和高度，单位为px
     *
     * @param context
     * @return
     */
    public static Point getScreenMetrics(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        int w_screen = dm.widthPixels;
        int h_screen = dm.heightPixels;
        return new Point(w_screen, h_screen);
    }

    /**
     * 获取屏幕高度，单位为px
     *
     * @param context
     * @return
     */
    public static int getScreenHeight(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        int h_screen = dm.heightPixels;
        return h_screen;
    }

    /**
     * 获取屏幕宽度，单位为px
     *
     * @param context
     * @return
     */
    public static int getScreenWidth(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        int w_screen = dm.widthPixels;
        return w_screen;
    }

    /**
     * 获取屏幕长宽比
     *
     * @param context
     * @return
     */
    public static float getScreenRate(Context context) {
        Point P = getScreenMetrics(context);
        float H = P.y;
        float W = P.x;
        return (H / W);
    }


    /**
     * 自动补齐小数点
     *
     * @param editText
     */
    public static void setPricePoint(final EditText editText, final addTextChangedListener addTextChangedListener) {
        editText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                String s = editable.toString();
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.indexOf(".") > 2) {
                        s = s.subSequence(0,
                                s.indexOf(".") + 3).toString();
                        editText.setText(s);
                        editText.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    editText.setText(s);
                    editText.setSelection(2);
                }

                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        editText.setText(s.subSequence(1, s.length()));
                        editText.setSelection(1);
                    }
                }

                if (addTextChangedListener != null) {
                    addTextChangedListener.onTextChanged(editText.getText().toString());
                }
            }
        });
    }

    public interface addTextChangedListener {
        void onTextChanged(String text);
    }


    private static addTextChangedListener addTextChangedListener;

    public void setAddTextChangedListener(addTextChangedListener addTextChangedListener) {
        this.addTextChangedListener = addTextChangedListener;
    }


    /**
     * 1、获取main在窗体的可视区域
     * 2、获取main在窗体的不可视区域高度
     * 3、判断不可视区域高度，之前根据经验值，在有些手机上有点不大准，现改成屏幕整体高度的1/3
     * 1、大于屏幕整体高度的1/3：键盘显示  获取Scroll的窗体坐标
     * 算出main需要滚动的高度，使scroll显示。
     * 2、小于屏幕整体高度的1/3：键盘隐藏
     *
     * @param main 根布局
     * @param scroll 需要显示的最下方View
     */
    static int bottomHight;

    public static void addLayoutListener(final View rootView, final View scroll) {
        scroll.postDelayed(new Runnable() {
            @Override
            public void run() {
                bottomHight = scroll.getHeight();
                rootView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
                    @Override
                    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                        if (bottom - oldBottom < -1) {
                            //软键盘弹上去了,动态设置高度为0
                            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                                    0);
                            scroll.setLayoutParams(params);
                        } else if (bottom - oldBottom > 1) {
                            //软键盘弹下去了，动态设置高度，恢复原先控件高度
                            //（"1"这个高度值可以换做：屏幕高度的1/3）
                            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                                    bottomHight);
                            scroll.setLayoutParams(params);
                        }
                    }
                });
            }
        }, 500);
    }


    public static void addLayoutListener(final View rootView, final View scroll, final int leftMargin, final int rightMargin, final int topMargin, final int bottomMargin) {
        scroll.postDelayed(new Runnable() {
            @Override
            public void run() {
                bottomHight = scroll.getHeight();
                rootView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
                    @Override
                    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                        if (bottom - oldBottom < -1) {
                            //软键盘弹上去了,动态设置高度为0
                            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                                    0);
                            scroll.setLayoutParams(params);
                        } else if (bottom - oldBottom > 1) {
                            //软键盘弹下去了，动态设置高度，恢复原先控件高度
                            //（"1"这个高度值可以换做：屏幕高度的1/3）
                            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                                    bottomHight);
                            params.leftMargin = leftMargin;
                            params.rightMargin = rightMargin;
                            params.topMargin = topMargin;
                            params.bottomMargin = bottomMargin;
                            scroll.setLayoutParams(params);
                        }
                    }
                });
            }
        }, 500);
    }

    /**
     * 设置Tab宽度
     *
     * @param mContext
     * @param tabLayout
     */
    public static void setTabWidth(final Context mContext, final TabLayout tabLayout, final int margin) {
        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                try {
                    //拿到tabLayout的mTabStrip属性
                    Field mTabStripField = tabLayout.getClass().getDeclaredField("mTabStrip");
                    mTabStripField.setAccessible(true);

                    LinearLayout mTabStrip = (LinearLayout) mTabStripField.get(tabLayout);

                    int dp10 = DisplayUtils.dip2px(mContext, margin);

                    for (int i = 0; i < mTabStrip.getChildCount(); i++) {
                        View tabView = mTabStrip.getChildAt(i);

                        //拿到tabView的mTextView属性
                        Field mTextViewField = tabView.getClass().getDeclaredField("mTextView");
                        mTextViewField.setAccessible(true);

                        TextView mTextView = (TextView) mTextViewField.get(tabView);
                        tabView.setPadding(0, 0, 0, 0);

                        //因为我想要的效果是   字多宽线就多宽，所以测量mTextView的宽度
                        int width = 0;
                        width = mTextView.getWidth();
                        if (width == 0) {
                            mTextView.measure(0, 0);
                            width = mTextView.getMeasuredWidth();
                        }

                        //设置tab左右间距为10dp  注意这里不能使用Padding 因为源码中线的宽度是根据 tabView的宽度来设置的
                        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tabView.getLayoutParams();
                        params.width = width;
                        params.leftMargin = dp10;
                        params.rightMargin = dp10;
                        tabView.setLayoutParams(params);

                        tabView.invalidate();
                    }

                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 关闭软键盘
     *
     * @param view
     * @param mContext 上下文
     */
    public static void closeKeybord(View view, Context mContext) {
        InputMethodManager imm = (InputMethodManager) mContext
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }


    /**
     * 切换文本和密码状态
     * @param isShowPassword
     * @param editText
     */
    public static void setPasswordLookState(boolean isShowPassword, EditText editText) {
        if (isShowPassword) {
            //设置文本为可见
            editText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        } else {
            //设置文本为密码
            editText.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }
        editText.postInvalidate();
        //切换后将EditText光标置于末尾
        CharSequence charSequence = editText.getText();
        if (charSequence instanceof Spannable) {
            Spannable spannableText = (Spannable) charSequence;
            Selection.extendSelection(spannableText, charSequence.length());
        }
    }



}
